package com.lancoo.znbkxx.teacher.utils;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.tt.util.httputil.EncodingUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.lancoo.znbkxx.teacher.utils.LancooUtils.isTablet;

public class WebStyleUtils {

    public static String Function_click = "<html>" +
            "<head>" +
            "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
            "    <script type=\"text/javascript\">" +
            "    function CalledByJavaCodeWithPara(id,arg) {" +
            "         document.getElementById(id).innerHTML = arg;" +
            "      }" +
            "    </script>" +
            "</head>" +
            "</html>";

    public static String Function_backgroundColor = "<html>" +
            "<head>" +
            "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
            "    <script type=\"text/javascript\">" +
            "    function setBackGroundColor(id,bgColor,Radius,BottomH) {" +
            "         document.getElementById(id).style.backgroundColor = bgColor;" +
            "         document.getElementById(id).style.borderRadius = Radius;" +
            "         document.getElementById(id).style.borderBottom = BottomH;" +
            "      }" +
            "    </script>" +
            "</head>" +
            "</html>";

    public static String Function_topHeight = "<html>" +
            "<head>" +
            "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
            "    <script type=\"text/javascript\">" +
            "  function topHeight(id) {" +
            "    var input = document.getElementById(id);" +
            "   　var actualTop = input.offsetTop;" +
            "　　　　var current = input.offsetParent;" +
            "　　　　while (current !== null){" +
            "　　　　　　actualTop += current. offsetTop;" +
            "　　　　　　current = current.offsetParent;" +
            "　　　　}" +
            "　　　　return actualTop;" +
            "      }" +
            "    </script>" +
            "</head>" +
            "</html>";

    public static String getWebString(String strAsk){
        //文字大小：font-size
        //文字行间距：line-height:18px;
        String strWebString= "<html> \n" +
                "<head> \n" +
                "<style type=\"text/css\"> \n" +
                "body {text-align:justify; font-size: "+16+"px!important; " +
                "line-height: "+(16+12)+"px!important;" +
                "color:#848484!important;" +
                "\"font-family:'Arial','Times New Roman', 'SimSun' !important\"}\n" +
                "</style> \n" +
                "</head> \n" +
                "<body>"+ EncodingUtils.getString(strAsk.getBytes(), "UTF-8")+"</body> \n </html>";
        return strWebString;
    }

    /**
     * 设置网页中图片的点击事件
     * @param view
     *
     */
    public static void setWebImageClick(WebView view,String method) {
        String jsCode="javascript:(function(){" +
                "var imgs=document.getElementsByTagName(\"img\");" +
                "for(var i=0;i<imgs.length;i++){" +
                "imgs[i].pos = i;"+
                "imgs[i].onclick=function(){" +
                "window."+method+".openImage(this.src,this.pos);" +
                "}}})()";
        view.loadUrl(jsCode);
    }

    public static String [] returnImageUrlsFromHtml(String htmlCode) {
        List<String> imageSrcList = new ArrayList<String>();
        Pattern p = Pattern.compile("<(?i)img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic|\\b)\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(htmlCode);
        String quote = null;
        String src = null;
        while (m.find()) {
            quote = m.group(1);
            src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("//s+")[0] : m.group(2);
            imageSrcList.add(src);
        }
        if (imageSrcList.size() == 0) {
            return null;
        }
        return imageSrcList.toArray(new String[imageSrcList.size()]);
    }


    //设置网页字体显示大小
    public static void initWebView(Context context, WebView wv){
        float fontScale = context.getResources().getConfiguration().fontScale;
        Log.e("==系统默认字体大小==","========系统默认字体大小========="+fontScale);

        WebSettings settings = wv.getSettings();

        if(isTablet(context)){
            settings.setTextZoom(110);
        }else {
            settings.setTextZoom(100); // 通过百分比来设置文字的大小，默认值是100。
        }

        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//自适应屏幕
        settings.setDomStorageEnabled(true);//是否开启本地DOM存储
        settings.setBlockNetworkImage(false);//是否开启本地DOM存储

    }

    public static void showWebViewCssStyle(Context context,WebView wv,String strAsk,boolean isIndentation){

        wv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        strAsk = Function_click + Function_backgroundColor + Function_topHeight + getWebString(strAsk);

        // 先把所有的style干掉 - 正则表达式(反向替换)
        strAsk = strAsk.replaceAll("(<span.*?)style=\".*?\"","$1");

        //没办法地办法(适配TD标签地style)
        String regEx_TD_PaddingTop = "PADDING-TOP: 0cm;";
        strAsk = strAsk.replaceAll(regEx_TD_PaddingTop,"PADDING-TOP: 5.4pt;");
        String regEx_TD_PaddingBottom = "PADDING-BOTTOM: 0cm;";
        strAsk = strAsk.replaceAll(regEx_TD_PaddingBottom,"PADDING-BOTTOM: 5.4pt;");

        initWebView(context, wv);

        strAsk = strAsk.replaceAll("(?i)<img", "<img style=max-width:90%;height:auto");//部分图片显示异常

        //最新屏蔽，适配平板横屏显示（手机需要开放）
        String newTableStyle = "<TABLE style=\"text-align:left;\"vertical-align:left;\"table-layout: fixed;\"" +
                " border=\"1\" width=\"100%\" cellspacing=\"0\" cellpadding=\"10\">";
        ArrayList<String> arrayStrList = getAllSatisfyStr(strAsk, "<TABLE(.*?)>");
        for (int i = 0; i < arrayStrList.size(); i++) {
            strAsk = strAsk.replaceAll(arrayStrList.get(i), newTableStyle);
        }

        getWebContent(wv, strAsk + "<br>",isIndentation);
    }

    //为了适配选词填空居中显示
    public static void showWebViewCssStyleAnother(Context context,WebView wv,String strAsk,boolean isIndentation){

        wv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        strAsk = Function_click + Function_backgroundColor + Function_topHeight + getWebString(strAsk);

        // 先把所有的style干掉 - 正则表达式
//        String regEx = " style=\"(.*?)\"";
        String regEx = "style=\"display:inline-block;height:20px;text-align:center;text-indent:0;\"";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(strAsk);
        if (m.find()) {
            strAsk = m.replaceAll("");
        }

        //没办法地办法(适配TD标签地style)
        String regEx_TD_PaddingTop = "PADDING-TOP: 0cm;";
        strAsk = strAsk.replaceAll(regEx_TD_PaddingTop,"PADDING-TOP: 5.4pt;");
        String regEx_TD_PaddingBottom = "PADDING-BOTTOM: 0cm;";
        strAsk = strAsk.replaceAll(regEx_TD_PaddingBottom,"PADDING-BOTTOM: 5.4pt;");

        initWebView(context, wv);

        String newTableStyle = "<TABLE style=\"text-align:center;\"vertical-align:left;\"table-layout: fixed;\"" +
                " border=\"0.5\" width=\"100%\" cellspacing=\"0\" cellpadding=\"10\">";
        ArrayList<String> arrayStrList = getAllSatisfyStr(strAsk, "<TABLE(.*?)>");
        for (int i = 0; i < arrayStrList.size(); i++) {
            strAsk = strAsk.replaceAll(arrayStrList.get(i), newTableStyle);
        }
        getWebContent(wv, strAsk + "<br>",isIndentation);
    }

    /**
     * 修改webview样式(assets--css文件)
     *
     * @param webview
     * @param ask
     */
    public static void getWebContent(WebView webview, String ask,boolean isIndentation) {

        webview.setBackgroundColor(0);
        webview.getBackground().setAlpha(2);

        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        String linkCss = "";
        if(isIndentation){
            linkCss = "<link rel=\"stylesheet\" href=\"file:///android_asset/NewCssStyle.css\" type=\"text/css\">";
        }else{
            linkCss = "<link rel=\"stylesheet\" href=\"file:///android_asset/CssStyle.css\" type=\"text/css\">";
        }
        String body = "<html><header>" + linkCss + "</header>" + ask
                + "</body></html>";
        webview.loadDataWithBaseURL(linkCss, body, "text/html", "UTF-8", null);
    }

    /**
     * 获取所有满足正则表达式的字符串
     * @param str 需要被获取的字符串
     * @param regex 正则表达式
     * @return 所有满足正则表达式的字符串
     */
    public static ArrayList<String> getAllSatisfyStr(String str, String regex) {
        if (str == null || str.isEmpty()) {
            return null;
        }
        ArrayList<String> allSatisfyStr = new ArrayList<>();
        if (regex == null || regex.isEmpty()) {
            allSatisfyStr.add(str);
            return allSatisfyStr;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            allSatisfyStr.add(matcher.group());
        }
        return allSatisfyStr;
    }

    public static boolean hasTable(String text) {
//        return text.matches("<TABLE.*?>[\\s\\S]*<\\/TABLE>");
//        return text.matches("<TABLE(.*?)>");
        return text.contains("<TABLE");
    }

}